//$Id: Main.java 33 2011-12-02 12:53:35Z cr.carbon@gmail.com $
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;

public class Main {
	
	private static Gamestate parseFile(String fileName) throws Exception {
		try {
			final String curDir = System.getProperty("user.dir");
            FileReader fileReader = new FileReader(curDir + fileName); 
            BufferedReader reader = new BufferedReader(fileReader);
            
            Gamestate currentGamestate = new Gamestate();
            
            String sCurrentPlayer = reader.readLine();            
            String sGamestate = reader.readLine();
            
            currentGamestate.parseGamestate(sGamestate);
            currentGamestate.parsePlayer(sCurrentPlayer);
            
            return currentGamestate;
            
		} catch (FileNotFoundException e) {
            e.printStackTrace();
		} catch (NumberFormatException e) {
            e.printStackTrace();
		} catch (IOException e) {
            e.printStackTrace();
		}	
		
		return null;
	}
	
	private static void parseOutput(Node root) throws Exception{

		System.out.println("root, " + root.getValueAssigned());

		LinkedList<Node> list = new LinkedList<Node>();
		list.add(root);
		while (!list.isEmpty()){
			Node n = list.pop();
			System.out.print(n.getParentsString() + ": ");
			ArrayList<Node> branches = n.getBranches();
			
			if (branches.size() == 0)
				System.out.println("terminal");

			for (int i = 0; i < branches.size(); i++){
				Node node = branches.get(i);
				System.out.print(node.getStringWithValue());
				list.add(node);
				if (i != branches.size() - 1)
					System.out.print(",");
				else System.out.println("");
			}

		}
	}


	public static void main(String[] args) throws Exception {
		Gamestate gamestate = parseFile("//" + args[0]);
		Node root = Logic.decidePath(gamestate);
		
		System.out.println(gamestate.getCurrentPlayer() + " to play (" + (root.getBestMove().getMoveX() + 1) + "," + (root.getBestMove().getMoveY() + 1) + ")");
		System.out.println("Search tree: ");
		parseOutput(root);
	}

}
